package com.mentaleye.biz.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mentaleye.bean.StudentsBean;
import com.mentaleye.biz.StudentsBiz;
import com.mentaleye.dal.model.Dictionary;
import com.mentaleye.dal.model.OaClassRelation;
import com.mentaleye.dal.model.Students;
import com.mentaleye.dal.model.UserLogin;
import com.mentaleye.enums.DictionaryEnums;
import com.mentaleye.service.DictionaryService;
import com.mentaleye.service.OaClassRelationService;
import com.mentaleye.service.StudentsService;
import com.mentaleye.service.UserLoginService;
import com.mentaleye.util.CommonPage;
import com.mentaleye.util.CommonResult;
import com.mentaleye.util.DateFormatter;
import com.mentaleye.util.FileUtils;
import com.mentaleye.util.ObjectUtil;
import com.mentaleye.util.StudentsUtil;

@Service
public class StudentsBizImpl implements StudentsBiz {

	private static Logger logger = Logger.getLogger(StudentsBiz.class);

	@Autowired
	private DictionaryService dictionaryService;

	@Autowired
	private OaClassRelationService relationService;

	@Autowired
	private StudentsService dataService;

	@Autowired
	private UserLoginService loginService;

	@Override
	public CommonResult insertData(StudentsBean dataBean) {
		String defaultPassword = null;
		dataBean.setGraduationDate(DateFormatter.parse(dataBean.getGraduationDateString(), "yyyy-MM"));
		CommonResult result = new CommonResult();
		List<Dictionary> dictionaryList = this.dictionaryService
				.queryDictionaryByParentId(DictionaryEnums.DEFAULT_PASSWORD.getCode());
		if (dictionaryList.isEmpty()) {
			defaultPassword = "888888";
		} else {
			defaultPassword = dictionaryList.get(0).getDictionaryValue();
		}

		UserLogin login = new UserLogin();
		login.setLoginId(dataBean.getStuId());
		login.setLoginName(dataBean.getStuId());
		login.setPassword(defaultPassword);
		login.setUserType(DictionaryEnums.STUDENT_TYPE.getCode());

		try {
			Students data = (Students) ObjectUtil.transfer(dataBean, Students.class);
			if (this.dataService.insertData(data)) {
				if (this.loginService.insertRecord(login)) {
					result.setIsSuccess(true);
					result.setResultMsg("添加成功！");
				} else {
					result.setResultMsg("添加失败！");
				}
			} else {
				result.setResultMsg("添加失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("添加异常！");
			logger.error("学生信息添加异常！", e);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CommonResult insertByList(List<StudentsBean> beanList) {
		String defaultPassword = null;
		CommonResult result = new CommonResult();
		List<Dictionary> dictionaryList = this.dictionaryService
				.queryDictionaryByParentId(DictionaryEnums.DEFAULT_PASSWORD.getCode());
		if (dictionaryList.isEmpty()) {
			defaultPassword = "888888";
		} else {
			defaultPassword = dictionaryList.get(0).getDictionaryValue();
		}

		UserLogin login = null;
		List<UserLogin> loginList = new ArrayList<UserLogin>();
		for (StudentsBean dataBean : beanList) {
			login = new UserLogin();
			login.setLoginId(dataBean.getStuId());
			login.setLoginName(dataBean.getStuId());
			login.setPassword(defaultPassword);
			login.setUserType(DictionaryEnums.STUDENT_TYPE.getCode());
			loginList.add(login);
		}

		try {
			List<Students> dataList = ObjectUtil.transferList(beanList, Students.class);
			if (this.dataService.insertByList(dataList)) {
				if (this.loginService.insertByList(loginList)) {
					result.setIsSuccess(true);
					result.setResultMsg("添加成功！");
				} else {
					result.setResultMsg("添加失败！");
				}
			} else {
				result.setResultMsg("添加失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("添加异常！");
			logger.error("学生信息添加异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult updateData(StudentsBean dataBean) {
		dataBean.setGraduationDate(DateFormatter.parse(dataBean.getGraduationDateString(), "yyyy-MM"));
		CommonResult result = new CommonResult();
		try {
			Students data = (Students) ObjectUtil.transfer(dataBean, Students.class);
			if (this.dataService.updateData(data)) {
				result.setIsSuccess(true);
				result.setResultMsg("更新成功！");
			} else {
				result.setResultMsg("更新失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("更新异常！");
			logger.error("学生信息更新异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult updateStateByMap(Map<String, Object> map) {
		CommonResult result = new CommonResult();
		try {
			if (this.dataService.updateStateByMap(map)) {
				result.setIsSuccess(true);
				result.setResultMsg("更新成功！");
			} else {
				result.setResultMsg("更新失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("更新异常！");
			logger.error("学生信息更新异常！", e);
		}
		return result;
	}
	
	@Override
	public CommonResult deleteByKeyList(List<Integer> idList) {
		List<String> stuIdList = new ArrayList<String>();
		CommonResult result = new CommonResult();
		try {
			List<Students> dataList = this.dataService.getListByIds(idList);
			if (!dataList.isEmpty()) {
				for (Students students : dataList) {
					stuIdList.add(students.getStuId());
				}

				if (this.loginService.deleteBySelective(stuIdList, DictionaryEnums.STUDENT_TYPE.getCode())) {
					if (this.dataService.deleteByList(idList)) {
						result.setIsSuccess(true);
						result.setResultMsg("删除成功！");
					} else {
						result.setResultMsg("删除失败！");
					}
				} else {
					result.setResultMsg("删除失败！");
				}
			} else {
				result.setResultMsg("删除失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("删除异常！");
			logger.error("学生信息删除异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult deleteByStuIdList(List<String> stuIdList) {
		List<Integer> idList = new ArrayList<Integer>();
		CommonResult result = new CommonResult();
		try {
			List<Students> dataList = this.dataService.getListByStuIds(stuIdList);
			if (!dataList.isEmpty()) {
				for (Students students : dataList) {
					idList.add(students.getId());
				}
				this.relationService.deleteBySystem(idList, DictionaryEnums.STUDENT_TYPE.getCode());
				if (this.loginService.deleteByLoginIdList(stuIdList)) {
					if (this.dataService.deleteByStuIdList(stuIdList)) {
						result.setIsSuccess(true);
						result.setResultMsg("删除成功！");
					} else {
						result.setResultMsg("删除失败！");
					}
				} else {
					result.setResultMsg("删除失败！");
				}
			} else {
				result.setResultMsg("删除失败！");
			}
		} catch (Exception e) {
			result.setResultMsg("删除异常！");
			logger.error("学生信息删除异常！", e);
		}
		return result;
	}

	@Override
	public Map<String, Object> getStudentMapById(Integer id) {
		Map<String, Object> dataBean = null;
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		try {
			List<Map<String, Object>> mapList = this.dataService.getListByMap(paramMap);
			if (!mapList.isEmpty()) {
				dataBean = mapList.get(0);
			}
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return dataBean;
	}

	@Override
	public List<Students> getList() {
		List<Students> dataList = null;
		try {
			dataList = this.dataService.getList();
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return dataList;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<StudentsBean> getBeanList() {
		List<StudentsBean> beanList = null;
		try {
			beanList =ObjectUtil.transferList(this.dataService.getList(), StudentsBean.class) ;
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return beanList;
	}

	@Override
	public void getListByPage(CommonPage page) {
		try {
			page.setPageData(this.dataService.getListByMap(page.pageToMap()));
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<StudentsBean> getListBeanByIds(List<Integer> idList) {
		List<StudentsBean> beanList = null;
		try {
			beanList = ObjectUtil.transferList(this.dataService.getListByIds(idList), StudentsBean.class);
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return beanList;
	}

	@Override
	public Students getStudentById(Integer id) {
		Students student = null;
		try {
			student = this.dataService.getStudentById(id);
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return student;
	}

	@SuppressWarnings("unchecked")
	@Override
	public CommonResult studentsToClass(Map<String, Object> paramMap) {
		CommonResult result = new CommonResult();
		List<String> idValueList = (List<String>) paramMap.get("idList");
		List<Integer> idList = new ArrayList<Integer>();
		for (String idValue : idValueList) {
			idList.add(Integer.valueOf(idValue));
		}

		Integer classId = Integer.valueOf(String.valueOf(paramMap.get("classId")));
		OaClassRelation relation = null;
		Calendar calendar = Calendar.getInstance();
		Date nowTime = calendar.getTime();
		try {
			List<OaClassRelation> relationList = this.relationService.getListBySystem(classId, idList);
			if (relationList.isEmpty()) {
				relationList = new ArrayList<OaClassRelation>();
				for (Integer id : idList) {
					relation = new OaClassRelation();
					relation.setPersonId(id);
					relation.setOaclassId(classId);
					relation.setCreateTime(nowTime);
					relation.setIncomeTime(nowTime);
					relation.setPersonType(DictionaryEnums.STUDENT_TYPE.getCode());
					relation.setRelationState(0);
					relationList.add(relation);
				}
				if (this.relationService.insertByList(relationList)) {
					result.setIsSuccess(true);
					result.setResultMsg("插入成功！");
				} else {
					result.setResultMsg("插入失败！");
				}
			} else {
				StringBuilder sb = new StringBuilder();
				idList = new ArrayList<Integer>();
				for (OaClassRelation classRelation : relationList) {
					idList.add(classRelation.getPersonId());
				}

				List<Students> stundentList = this.dataService.getListByIds(idList);
				for (int i = 0; i < stundentList.size(); i++) {
					sb.append(stundentList.get(i).getStuName() + "\n");
				}
				sb.append("已经分配班级！");
				result.setResultMsg(sb.toString());
			}
		} catch (Exception e) {
			logger.error("插入学生关联班级信息异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult studentChangeClass(Map<String, Object> paramMap) {
		CommonResult result = new CommonResult();
		Integer id = Integer.valueOf(paramMap.get("id").toString());
		Integer newClassId = Integer.valueOf(paramMap.get("newClassId").toString());
		String updateDesc = (String) paramMap.get("updateDesc");
		Calendar calendar = Calendar.getInstance();
		try {
			OaClassRelation relation = this.relationService.getByPersonId(id);
			if (relation != null) {
				relation = new OaClassRelation();
				relation.setPersonId(id);
				relation.setOaclassId(newClassId);
				relation.setUpdateTime(calendar.getTime());
				relation.setUpdateDesc(updateDesc);
				relation.setPersonType(DictionaryEnums.STUDENT_TYPE.getCode());

				if (this.relationService.updateOaClassRelationBySelective(relation)) {
					result.setIsSuccess(true);
					result.setResultMsg("更新成功！");
				} else {
					result.setResultMsg("更新失败！");
				}
			} else {
				result.setResultMsg("该班级未分配班级！");
			}

		} catch (Exception e) {
			logger.error("更新学生关联班级信息异常！", e);
		}
		return result;
	}

	@Override
	public CommonResult StudentsDrop(Integer id) {
		CommonResult result = new CommonResult();
		try {

			Students student = this.dataService.getStudentById(id);
			if (student.getState()==DictionaryEnums.NO_INTO_CLASS.getCode()) {
				result.setResultMsg("该学生还未入学！");
			} else {
				student.setState(DictionaryEnums.STUDENT_DROP.getCode());
				if (this.dataService.updateStateById(student)) {
					result.setIsSuccess(true);
					result.setResultMsg("更新成功！");
				} else {
					result.setResultMsg("更新失败！");
				}
			}
		} catch (Exception e) {
			logger.error("更新学生关联班级信息异常！", e);
		}
		return result;
	}

	@Override
	public List<Students> getStuByRoleNo(Integer roleNo) {
		List<Students> list = null;
		try {
			list = dataService.queryStuByRoleId(roleNo);
		} catch (Exception e) {
			logger.error("查询除关联角色的所有学生异常", e);
		}
		return list;
	}

	public List<StudentsBean> queryListByState(Integer state) {
		List<StudentsBean> list = null;
		try {
			list = dataService.queryListByState(state);
		} catch (Exception e) {
			logger.error("按状态查询学生异常", e);
		}
		return list;
	}

	@Override
	public CommonResult fileUpload(MultipartFile myfile, HttpServletRequest request) {
		CommonResult result = new CommonResult();
		if (myfile.isEmpty()) {
			result.setResultMsg("上传文件不能为空");
		} else {
			String originalFilename = myfile.getOriginalFilename();// 得到文件名字

			try {
				String genePicPath = request.getSession().getServletContext().getRealPath("/upload/");
				FileUtils.upload(myfile.getInputStream(), genePicPath, originalFilename);
				result.setIsSuccess(true);
				result.setResultMsg("文件上传成功");
			} catch (Exception e) {
				result.setResultMsg("文件上传异常");
			}
		}
		return result;
	}

	@Override
	public CommonResult excelImport(String filename, HttpServletRequest request) {
		CommonResult result = new CommonResult();
		String genePicPath = request.getSession().getServletContext().getRealPath("/upload/");
		String strm[] = filename.split("=");

		String file = strm[strm.length - 1];// 最后一分号内容
		String path = genePicPath + "\\" + file;

		List<Students> dataList = StudentsUtil.readExcel(path);
		try {
			if (this.dataService.insertByList(dataList)) {
				result.setIsSuccess(true);
				result.setResultMsg("数据导入成功");
			} else {
				result.setResultMsg("数据导入失败");
			}
		} catch (Exception e) {
			result.setResultMsg("数据导入异常");
		}
		return result;
	}

	@Override
	public List<Map<String, Object>> getMapByClassName(Map<String,Object> paramMap) {
		List<Map<String, Object>> mapList =null;
		try {
			mapList = this.dataService.getListByMap(paramMap);
		} catch (Exception e) {
			logger.error("查询学生信息异常！", e);
		}
		return mapList;
	}
}
